package com.lv.suyiyong.hfr.ui

import android.content.Intent
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lv.common.base.BaseActivity
import com.lv.common.dialog.SwipeCatpchaDialog
import com.lv.common.im.GenerateTestUserSig
import com.lv.common.imp.OnDialogSureListener
import com.lv.common.ktx.setSafeListener
import com.lv.common.network.model.DataResult
import com.lv.common.network.support.YgxUtils
import com.lv.common.thirdparty.ShareUtils
import com.lv.common.utils.*
import com.lv.common.utils.YgxUtilsKt.Companion.sendCode
import com.lv.common.widget.textview.SpanTextView
import com.lv.service.event.ThreeLandingEvent
import com.lv.service.model.ServiceViewModel
import com.lv.service.net.RegistUserReqBody
import com.lv.service.net.SendCodeBody
import com.lv.service.net.ThreedLoginReqBody
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.service.webview.ConsealWebActivity
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.databinding.ActivityRegistBinding
import com.lv.suyiyong.hfr.moudel.MainViewModel
import com.tencent.qcloud.tuicore.TUILogin
import com.tencent.qcloud.tuicore.interfaces.TUICallback
import com.ygx.zxing.utils.CodeUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 作者： ygx
 * 创建日期：2023/3/2 7:26 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：注册页面
 */
@Route(path = ARoutUtils.RegistActivityURL)
class RegistActivity : BaseActivity<ActivityRegistBinding>(), View.OnClickListener {
    private var timer: TimerUnit? = null
    private val viewModelService: ServiceViewModel by viewModel()
    private val viewModel: MainViewModel by viewModel()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    override fun getLayoutRes() = R.layout.activity_regist
    override fun initView() {
        super.initView()
        initStatusBar(this, true, true)

        mBinding.apply {
            vm = viewModel
            StatusBarUtil.setHeightAndPadding(this@RegistActivity, titleBar)
            mBinding.titleBar.onClickBackIcon() { finish() }
            tvLogin.setOnClickListener(this@RegistActivity)
            tvAgree.setOnClickListener {
                cbBox.isChecked = !cbBox.isChecked
            }
            etPhone.addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(
                    s: CharSequence,
                    start: Int,
                    count: Int,
                    after: Int
                ) {
                }

                override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
//                    etPhone.paint.isFakeBoldText = !TextUtils.isEmpty(s)
                    if (s.length == 11) {
                        etCode.requestFocus()
                    }
                }

                override fun afterTextChanged(s: Editable) {
                }
            })

            mBinding.tvCode.setSafeListener {
//                startLoading("发送中……")
                val phone = viewModel.obMobile.get()
                if (phone.isNullOrEmpty() || phone.length < 11) {
                    showToast(this@RegistActivity, "请输入11位手机号")
                } else {
                    if (viewModel.obIsAgree.get() == true) {
                        showSwipecaptDialog(phone)
                    } else {
                        showToast(this@RegistActivity, "请同意服务条款")
                    }
                }

            }

            mBinding.btnLogin.setSafeListener {
//                startLoading()
                var invite = mBinding.etInvite.text.trim().toString()
                if (invite.isEmpty()) {
                    invite = ""
                }
                registUser(
                    RegistUserReqBody(
                        viewModel.obMobile.get()!!, viewModel.obPassword.get()!!, invite
                    )
                )
            }
            mBinding.ivScan.setSafeListener {
                checkPermission()
            }
            mBinding.tvAgree.setText(createSpanTexts()) {
                ConsealWebActivity.openUrl(this@RegistActivity, "0")
            }

        }
    }

    private fun registUser(body: RegistUserReqBody) {
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { viewModelService.registUser(body) }.await()
            parseRegistUserResult(result)
        }
    }

    private fun parseRegistUserResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<UserInfo> { code, data, message, result ->
                ARouter.getInstance().build(ARoutUtils.PerfectUserInfoActivity)
                    .withParcelable("userInfo", data).withBoolean("showLogin", true).navigation()
                finish()
            }
            onBizError<Any> { code, message, data ->
                showToast(message)

            }
        }
    }

    private fun sendCode(phone: String, sendcode: String) {
        val body = SendCodeBody(phone, sendcode)
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { viewModelService.sendCode(body) }.await()
            parseSendCodeResult(result)
        }
    }

    private fun parseSendCodeResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<Any> { code, data, message, result ->
                if (timer == null) {
                    timer = TimerUnit(mBinding.tvCode)
                }
                timer?.startTime()
                showToast(message ?: "")

            }
            onBizError<Any> { code, message, data ->
                showToast(message)

            }
        }
    }

    private fun threeLanding(body: ThreedLoginReqBody) {
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { viewModelService.threeLanding(body) }.await()
            parseThreeLandingResult(result)
        }
    }

    private fun parseThreeLandingResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<Any> { code, data, message, result ->


            }
            onBizError<Any> { code, message, data ->
                showToast(message)

            }
        }
    }

    private fun checkPermission() {
        PermissionXUtils.checkPermissionCameraRead(
            this,
            resources.getString(com.lv.common.R.string.permission_scan_read),
            callback = object : PermissionXUtilsCallback {
                override fun permissionCallback(
                    allGranted: Boolean,
                    grantedList: List<String?>,
                    deniedList: List<String?>
                ) {
                    if (allGranted) {
                        ARouter.getInstance().build(ARoutUtils.CaptureactivityURL)
                            .navigation(this@RegistActivity, Constants.RESPOND_CAPTURE)
                    }
                }

                override fun fotPermsission() {
                }
            })
    }

    private fun showSwipecaptDialog(phone: String) {
        val swipeCatpchaDialog =
            SwipeCatpchaDialog(this, true, true, object : OnDialogSureListener {
                override fun onSureClick(content: String?) {
                    val sendCode = sendCode(phone)
                    sendCode(phone, sendCode)
                }
            })
        swipeCatpchaDialog.show()
    }


    override fun initConfig() {
        super.initConfig()


    }

    private fun login(res: UserInfo?) {
        res?.let {
            YgxUtilsKt.setAppToken(it.token, it.refreshtoken, it.id)

            // 在用户 UI 点击登录的时候调用
            TUILogin.login(
                this@RegistActivity,
                GenerateTestUserSig.SDKAPPID,
                it.txaccid,
                it.txaccidpassword,
                object : TUICallback() {
                    override fun onError(code: Int, desc: String) {
//                        loadFinished()
                        LogUtils.e("onError")
                    }

                    override fun onSuccess() {
//                        loadFinished()
                        UserDbHelper.insertUserInfo(this@RegistActivity, res)
                        ARouter.getInstance().build(ARoutUtils.PerfectUserInfoActivity).navigation()
                        YgxUtilsKt.sendMessgeToSelf(it.txaccid, it.phone)

                        finish()
                    }
                })
        }
    }

    override fun initData() {
        super.initData()
        LiveEventBus.get(
            ThreeLandingEvent::class.java,
        ).observe(
            this
        ) { s ->
            if (s != null && s.tag == 0) {
                val openid = YgxUtils.encodeWithUtf8(s.openid)
                val threedLoginReqBody = ThreedLoginReqBody(openid, "0")
                threeLanding(threedLoginReqBody)
            }
        }
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.tv_login -> {
                ARouter.getInstance().build(ARoutUtils.OneKeyLoginActivityURL).navigation()
                finish()
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != RESULT_OK) {
            return
        }
        if (requestCode == Constants.RESPOND_CAPTURE) {
            //扫一扫
            val result = data!!.getStringExtra(CodeUtils.RESULT_STRING)
            //https://www.suyiyong.cn/code?SYY_PopularizeDownload=123456  邀请码
            if (result!!.contains("SYY_PopularizeDownload")) {
                val split = result.split("=").toTypedArray()
                split.let {
                    if (split.size > 1) {
                        LogUtils.e("result", result)
                        mBinding.etInvite.setText(split[1])
                    }
                }
            }
        } else
            if (data != null) {
                //QQ回调
                ShareUtils.get().onQqActivityResult(requestCode, resultCode, data)
            }
    }

    private fun createSpanTexts(): List<SpanTextView.BaseSpanModel>? {
        val spanModels: MutableList<SpanTextView.BaseSpanModel> = ArrayList()
        var textSpanModel = SpanTextView.TextSpanModel()
        textSpanModel.content = "我已经阅读并同意"
        spanModels.add(textSpanModel)
        var spanModel = SpanTextView.ClickSpanModel()
        spanModel.content = "《亨富然隐私政策》"
        spanModels.add(spanModel)
//        textSpanModel = SpanTextView.TextSpanModel()
//        textSpanModel.content = "，未注册的手机号将自动创建亨富然账号"
//        spanModels.add(textSpanModel)
//        spanModel = ClickSpanModel()
//        spanModel.content = "Lucy"
//        spanModels.add(spanModel)
        return spanModels
    }


}